package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"week_exam_2_3/api/request"
	"week_exam_2_3/global"
	"week_exam_2_3/internal/model"
)

func FriendFind(context *gin.Context) {
	var friend_find request.FriendFindRequest
	if err := context.ShouldBind(&friend_find); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	var user model.User
	context.Request.ParseForm()
	user_str := context.Request.Form.Get("user")
	json.Unmarshal([]byte(user_str), &user)
	var friend model.User
	if err := global.DB.Model(&model.User{}).Joins("join friends on friends.seed_id = users.id").Where("users.name like ? and friends.user_id = ?", "%"+friend_find.Name+"%", user.ID).Find(&friend).Limit(1).Error; err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": err,
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查询成功",
		"data":    friend,
	})
	return
}
